<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽案例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .nav {
            height: 50px;
            line-height: 50px;
            background-color: pink;
        }

        .nav>a {
            text-decoration: none;
            font-size: 30px;
            margin-left: 50px;
        }

        .box {
            position: absolute;
            top: 50%;
            left: 50%;
            /* transform: translate(-50%,-50%); */
            margin-left: -150px;
            margin-top: -150px;
            width: 300px;
            height: 300px;
            border: 1px solid #000000;
        }

        .box>h2 {
            background-color: orange;
            height: 50px;
            font-size: 18px;
            line-height: 50px;
            cursor: move;
        }

        .box>h2>span {
            float: right;
            margin-right: 10px;
        }
    </style>
</head>

<body>
    <div class="nav">
        <a href="#">注册信息</a>
    </div>
    <div class="box">
        <h2>
            注册信息(可以拖拽)
            <span>关闭</span>
        </h2>
    </div>
</body>
<script>
    var box = document.querySelector('.box')
    var drag = document.querySelector('h2')

    drag.onmousedown = function (event) {
        event = event || window.event
        var initLeft = event.clientX
        var initTop = event.clientY
        var x = box.offsetLeft
        var y = box.offsetTop
        document.onmousemove = function (event) {
            event = event || window.event
            var moveX = event.clientX - initLeft + x + box.offsetWidth / 2
            var moveY = event.clientY - initTop + y + box.offsetHeight / 2

            box.style.left = moveX + 'px'
            box.style.top = moveY + 'px'

            window.getSelection() ? window.getSelection().removeAllRanges() : document.selection.empty();

        }

        document.onmouseup = function () {
            document.onmousemove = ''
        }

    }

</script>

</html>